package com.example.environment.inject;

import com.example.environment.inject.config.ConfigTest;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.env.ConfigurableEnvironment;

// 使 PropertiesFactoryBean 生效
@ImportResource("classpath:access-config.xml")
public class EnvironmentInjectDemo {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册 Configuration Class
        context.register(EnvironmentInjectDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();

        ConfigurableEnvironment environment = context.getEnvironment();
        try {
            // 测试 IOC 容器没有 ConfigTest Bean，因为没有扫描这个包，也没有添加注解
            ConfigTest configTest = context.getBean(ConfigTest.class);
        } catch (Exception e) {
            System.err.println("测试 IOC 容器没有 ConfigTest Bean: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.access.boot.sample.ConfigTest' available");
        }

        // 手动绑定 PropertiesFactoryBean 注入的环境变量
        // 绑定环境变量前缀为 config.test 的属性到 ConfigTest 中
        BindResult<ConfigTest> bind = Binder.get(environment).bind("config.test", ConfigTest.class);
        if (bind.isBound()) {
            ConfigTest configTest = bind.get();
            System.out.println(configTest);
        }

        // 关闭 Spring 应用上下文
        context.close();
    }
}
